package com.tangqi.sql;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

/**
 * 
 * @author tangqi
 * 通过文本文件读取SQL 语句
 */
public class GetSqlFromFile {
	
	/**
	 * 
	 * @param filename
	 * @return
	 */
	public String getSQL(String filename) {
        try {
            File file = new File(filename);
            if (!file.exists() || !file.canRead()) {
                return null;
            }
            if (file.isDirectory()) {
                return null;
            }
            FileReader fr = new FileReader(filename);
            BufferedReader in = new BufferedReader(fr);
            
            String sql_line;
            String sql_stat = "";
            while ((sql_line = in.readLine()) != null) {
                String new_sql_line;
                //if exist "--", ignore content after "--"
                if (sql_line.indexOf("--") >= 0) {
                    new_sql_line = sql_line.substring(0, sql_line.indexOf("--"));
                } else {
                    new_sql_line = sql_line;
                }
                sql_stat += new_sql_line + " ";
                sql_line = "";
            }
            return sql_stat;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
